package ynu.czs.controller;

import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import ynu.czs.entity.Cart;
import ynu.czs.entity.CommonResult;
import ynu.czs.entity.User;
import ynu.czs.feign.ServiceProviderService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/cart")
@RefreshScope
public class CartController {

    @Resource
    private ServiceProviderService serviceInstance;  // 注入Feign客户端

    @GetMapping("/getUser/{userId}")
    @LoadBalanced
    @CircuitBreaker(name = "bulkheadA",fallbackMethod = "getCartByIdDown")
    public CommonResult<Cart> getCartById(@PathVariable("userId") Integer userId) {
        CommonResult<Cart> result = new CommonResult<>();
        System.out.println("启动！");
        Integer code = 200;
        String message = "success";
        Cart cart = new Cart();
        List<String> goods = new ArrayList<>();
        goods.add("电池");
        goods.add("充电器");
        goods.add("手机壳");
        cart.setGoodList(goods);
        User u = serviceInstance.getUserById(userId);
        cart.setUser(u);
        result.setCode(code);
        result.setMsg(message);
        result.setResult(cart);
        System.out.println("结束！");
        return result;
    }

    public CommonResult<Cart> getCartByIdDown(Integer userId, Exception e) {
        String errorMsg = "服务器挤不下了，请稍后再试！";
        System.out.println(errorMsg);
        Integer code = 500;
        CommonResult<Cart> result = new CommonResult<>();
        result.setCode(code);
        result.setMsg(errorMsg);
        result.setResult(new Cart());
        return result;
    }

    @PostMapping("/createUser")
    @LoadBalanced
    @Bulkhead(name="bulkheadA",type = Bulkhead.Type.SEMAPHORE,fallbackMethod = "createUserDown")
    public User createUser(@RequestBody User user) {
        return serviceInstance.createUser(user);
    }

    public User createUserDown(User user, Throwable e) {
        e.printStackTrace();
        String errorMsg = "创建用户服务当前不可用，请稍后再试！用户信息：" + user.toString();
        System.out.println(errorMsg);
        // 返回降级响应（自定义默认用户或错误标记）
        return new User(-1, "fallback-user", "服务降级：用户创建失败");
    }

    @PutMapping("/updateUser/{userId}")
    @LoadBalanced
    @TimeLimiter(name = "timelimiterA", fallbackMethod = "updateUserDown")
    public CompletableFuture<User> updateUser(
            @PathVariable("userId") Integer userId,
            @RequestBody User user) {

        return CompletableFuture.supplyAsync(() -> {
            serviceInstance.updateUser(userId, user);
            return user;  // 返回更新后的用户对象
        });
    }

    public CompletableFuture<User> updateUserDown(
            Integer userId,
            User user,
            Throwable e) {  // 注意参数顺序

        String errorMsg = "用户更新服务超时，请稍后重试！用户ID：" + userId;
        System.out.println(errorMsg);
        e.printStackTrace();

        // 返回降级响应（自定义默认用户）
        return CompletableFuture.completedFuture(
                new User(-1,"fallback-user", "服务降级：更新失败")
        );
    }

    @DeleteMapping("/deleteUser/{userId}")
    @CircuitBreaker(name = "backendB",fallbackMethod = "deleteUserDown")
    public CommonResult<Cart> deleteUser(@PathVariable("userId") Integer userId) {
        CommonResult<Cart> result = new CommonResult<>();
        Integer code = 200;
        String message = "已触发删除操作";
        serviceInstance.deleteUser(userId);
        System.out.println(message);
        result.setCode(code);
        result.setMsg(message);
        return result;
    }

    public CommonResult<Cart> deleteUserDown(Integer userId, Exception e) {
        String errorMsg = "获取用户"+userId+"的信息服务当前出现了问题请稍后再试！";
        Integer code = 500;
        CommonResult<Cart> result = new CommonResult<>();
        System.out.println(errorMsg);
        result.setCode(code);
        result.setMsg(errorMsg);
        return result;
    }
}
